from aircraft.aircraft_sprite import *


class play_game(object):
    def __init__(self):
        """
            1. 创建游戏窗口
            2. 创建游戏时钟
            3. 创建精灵组
            4. 设置定时器
        """
        print(WINDOW_RECT)
        self.screen = pygame.display.set_mode(WINDOW_RECT.size)
        self.clock = pygame.time.Clock()
        self._create_sprite()
        pygame.time.set_timer(EMEMY_ID, 1000)

        pygame.time.set_timer(HERO_FIRE_EVENT, 500)

    def _create_sprite(self):
        bg_sprite11 = bg_sprite()
        bg_sprite1 = bg_sprite(True)
        self.enemy_sprite_group = pygame.sprite.Group()
        self.bg_sprite_group = pygame.sprite.Group(bg_sprite11, bg_sprite1)

        """英雄精灵组"""
        self._hero = hero()
        self.hero_group = pygame.sprite.Group(self._hero)

    """
    开始游戏（在游戏循环中）

1. 设置刷新频率
2. 调用事件监听方法
   1. 获取当前监听事件，根据事件id执行对应操作
3. 调用碰撞检测
4. 调用更新精灵组
   1. 更新精灵组
   2. 将精灵组绘画到窗口
5. pygame.display.update()
    """

    def start_game(self):
        print("游戏开始")
        while True:
            self.clock.tick(60)
            # print("qwe")
            self._event_monitor()
            self.impact_checking()
            self.update_script_group()
            pygame.display.update()

    def _event_monitor(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.game_over()
            elif event.type == EMEMY_ID:
                # print("进来了")
                enemy = enemy_sprite()
                self.enemy_sprite_group.add(enemy)
            elif event.type == HERO_FIRE_EVENT:
                # print("qwe")
                self._hero.fire()
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_RIGHT]:
            self._hero.speed = 5
        elif key_pressed[pygame.K_LEFT]:
            self._hero.speed = -5
        else:
            self._hero.speed = 0

    def impact_checking(self):
        pygame.sprite.groupcollide(self._hero.bullet_group, self.enemy_sprite_group, True, True)
        enemy_list = pygame.sprite.spritecollide(self._hero, self.enemy_sprite_group, True)
        if len(enemy_list) > 0:
            self._hero.kill()
            self.game_over()

    def update_script_group(self):
        self.bg_sprite_group.update()
        self.bg_sprite_group.draw(self.screen)
        self.enemy_sprite_group.update()
        self.enemy_sprite_group.draw(self.screen)

        self.hero_group.update()
        self.hero_group.draw(self.screen)

        self._hero.bullet_group.update()
        self._hero.bullet_group.draw(self.screen)

    @staticmethod
    def game_over():
        pygame.quit()
        exit()


if __name__ == '__main__':
    game = play_game()
    game.start_game()
